﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SimpleRest.Core.Routing;

namespace SimpleRest.Core.Extensions
{
    public delegate void AutoRegistrationEventHandler(Configuration configuration);

    public class AutoRegisterHttpModule : IHttpModule
    {
        static AutoRegisterHttpModule()
        {
            AutoRegistrationInitialization += new AutoRegistrationEventHandler(AutoRegisterHttpHandler_AutoRegistrationInitialization);
        }
        static void AutoRegisterHttpHandler_AutoRegistrationInitialization(Configuration configuration)
        {
        }

        private static bool IsInitialized = false;
        public static event AutoRegistrationEventHandler AutoRegistrationInitialization;

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            if (!IsInitialized)
            {
                IsInitialized = true;

                Configuration configuration = null;
                AutoRegistrationInitialization(configuration);
                if (configuration == null)
                    configuration = ConfigurationFactory.CreateConfiguration();

                var assembilies = AppDomain.CurrentDomain.GetAssemblies().Where(
                        d => !d.FullName.StartsWith("System") &&
                        !d.FullName.StartsWith("Microsoft")).ToArray();

                ServiceDiscoveryFactory.ScanAndRegisterServices(configuration, assembilies);
            }
        }
    }
}
